package com.yingxin.yxerp.module.appversion.manager;

import com.yingxin.yx.framework.user.dto.UserDto;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Sign {
    static String requestAuthSecret = "testSecret";

    /**
     * 签名
     * @param params
     * @param nonce 随机字符串
     * @param timestamp 时间戳
     * @return
     */
    public static String getSignature (Map<String, String> params, String nonce, long timestamp) {
        String paramsStr = getParamsString(params);
        String algorithm = "HmacSHA256";
        Mac hmacSha256;
        String digestHexString = null;

        try {
            hmacSha256 = Mac.getInstance(algorithm);

            String key = new StringBuilder().append(requestAuthSecret).append(nonce).toString();
            String message = new StringBuilder().append(Long.toString(timestamp)).append(paramsStr).toString();

            byte[] keyBytes = key.getBytes("utf-8");
            byte[] messageBytes = message.getBytes("utf-8");

            hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, algorithm));
            byte[] digestBytes = hmacSha256.doFinal(messageBytes);

            digestHexString = byteArrayToHexString(digestBytes);
        } catch (Exception e) {
            System.out.println("[ERROR] not supposed to happen: " + e.getMessage());
        }

        return digestHexString.toUpperCase();
    }

    private static String getParamsString (Map<String, String> params) {

        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < keys.length; i ++) {
            String key = keys[i];

            if (i != 0) {
                sb.append("&");
            }

            sb.append(key).append("=").append(params.get(key));
        }

        return sb.toString();
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b!=null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString();
    }

    /**
     * 随机字符串
     * @param length 数量
     * @return
     */
    public static String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder();
        String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        int charLength = characters.length();

        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * charLength);
            sb.append(characters.charAt(index));
        }

        return sb.toString();
    }

    /**
     * 生产签名登录
     * @param length 随机字符串
     * @return
     */
    public static Map<Object,Object> getSign(int length, UserDto userDto){
        // String nonce = Sign.generateRandomString(length);
        String nonce = "xxxxxx";
        long timestamp = System.currentTimeMillis();
        Map<String, String> params = new HashMap<String, String>();
        params.put("foo", "1");
        params.put("bar", "2");
        params.put("foo_bar", "4");
        params.put("foobar", "3");
        params.put("externalUid", userDto.getUserId());
        params.put("nickname", userDto.getStaffName());
        String signature = Sign.getSignature(params, nonce, timestamp);
        Map<Object, Object> map = new HashMap<Object, Object>();
        map.put("nonce",nonce);
        map.put("timestamp",timestamp);
        map.put("signature",signature);
        map.put("externalUid",userDto.getUserId());
        map.put("nickname",userDto.getStaffName());
        return map;
    }
}
